package com.yd.mvc.baseController;

import com.yd.app.util.BusinessException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.OutputStream;

/**
 * Created by zg
 * 组织机构增删改查
 */
@Controller
@RequestMapping(value = "/dapi/download")
public class DownloadController extends BaseController {

    @Value("${base.img.url}")
    private String base_img_url;
    @Value("${export.url}")
    private String export_url;
    @ResponseBody
    @RequestMapping(value = "/getfile", method = RequestMethod.GET)
    public void uploadimage(@RequestParam String url, HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("utf-8");
        String[] strs=url.split("/");
        String fileName=strs[strs.length-1];
        downloadByUrl(response,base_img_url+url,fileName);

    }
    @ResponseBody
    @RequestMapping(value = "/getexportfile", method = RequestMethod.GET)
    public void getexportfile(@RequestParam String url, HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("utf-8");
        String[] strs=url.split("/");
        String fileName=strs[strs.length-1];
        downloadByUrl(response,export_url+url,fileName);

    }

    //获取图片
    @ResponseBody
    @RequestMapping(value = "/getImageIO", method = RequestMethod.GET)
    public void upload(@RequestParam String imgUrl,HttpServletRequest request,HttpServletResponse response)throws Exception {
        imgUrl=new String(imgUrl.getBytes("iso8859-1"),"utf-8");
        request.setCharacterEncoding("utf-8");
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(base_img_url+imgUrl);
        } catch (FileNotFoundException e) {
            throw new BusinessException(404,"该图片不存在");
        }
        int i = inputStream.available();
        //byte数组用于存放图片字节数据
        byte[] buff = new byte[i];
        inputStream.read(buff);
        //记得关闭输入流
        inputStream.close();
        //设置发送到客户端的响应内容类型
        response.setContentType("image/*");
        OutputStream out = response.getOutputStream();
        out.write(buff);
        //关闭响应输出流
        out.close();

    }
}
